<template>
  <div>
    <UserAgreement :visible="agreement" @closeModel="closeAgreement" />
    <PrivacyAgreement :visible="privacy" @closeModel="closeAgreement" />
    <el-dialog
      class="login-dialog-wrapper"
      :visible="visible"
      v-if="step == 1"
      @close="closeModel"
    >
      <template slot="title"
        ><div class="login-title">登录后开始使用</div></template
      >
      <div class="login-body">
        <el-input
          class="phone-input"
          v-model="userPhone"
          placeHolder="请输入手机号"
          @change="handelNumberChange"
        >
          <span slot="prefix" class="phone-input-prefix">+86 </span></el-input
        >
        <span class="validate-falied">{{
          phoneValidate ? '' : '手机号码错误'
        }}</span>
        <el-button
          class="login-body-button"
          type="primary"
          :disabled="userPhone == ''"
          @click="handelNext"
          >下一步</el-button
        >
      </div>
      <template slot="footer">
        <div class="footer-agreement">
          <div class="login-agreement">
            <el-checkbox v-model="checked" @change="agreementChange">
              登录即代表您同意萌医大模型的<span
                class="agreenment"
                @click="showAgreement"
                >《用户协议》</span
              >与<span class="agreenment" @click="showPrivacy"
                >《隐私政策》</span
              >
            </el-checkbox>
          </div>
          <span class="validate-falied agree">{{
            agreeValidate ? '' : '请同意协议'
          }}</span>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      class="login-dialog-wrapper"
      :visible="visible"
      v-if="step == 2"
      @close="closeModel"
    >
      <template slot="title"
        ><div class="login-title">
          <i class="el-icon-arrow-left return-icon" @click="returnLastStep"></i
          >请输入6位验证码
        </div></template
      >
      <div class="login-body">
        <div class="code-info-text">
          <span>{{ '验证码已发送至 +86 ' + userPhone }}</span>
          <span
            :class="countdown == 0 ? 'code-resend' : 'code-resend disabled'"
            @click="sendCode"
            >{{ `重新发送 ${countdown == 0 ? '' : countdown + 's'}` }}</span
          >
        </div>
        <div class="code-container">
          <el-input
            class="code-single"
            v-for="(item, index) in codes"
            :key="index"
            :ref="'code' + index"
            v-model="codes[index]"
            maxlength="1"
            @input="handelCodeInputChange(index)"
            @keyup.enter.native="handleEnter(index)"
            @keyup.backspace.native="handleBackspace(index)"
          ></el-input>
        </div>
        <span class="validate-falied" v-if="!codeValid">验证码错误</span>
      </div>
      <template slot="footer">
        <el-button
          class="login-footer-button"
          type="primary"
          :disabled="codes.includes(undefined) || !codeValid"
          @click="handelNext"
          >下一步</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { setCookie } from '../utils/setCookie'
  import request from '../utils/request'
  import axios from 'axios'
  import UserAgreement from './userAgreement.vue'
  import PrivacyAgreement from './privacyAgreement.vue'
  export default {
    name: 'LoginModel',
    props: {
      visible: Boolean,
    },
    components: { UserAgreement, PrivacyAgreement },
    data() {
      return {
        userPhone: '',
        checked: false,
        step: 1, //1输入手机号，2输入验证码
        phoneValidate: true,
        agreeValidate: true,
        codes: [
          undefined,
          undefined,
          undefined,
          undefined,
          undefined,
          undefined,
        ],
        currentCodeIndex: 0,
        codeValid: true,
        countdown: 0,
        agreement: false,
        privacy: false,
      }
    },
    computed: {},
    watch: {
      step(n, o) {
        if (n == 2) {
          this.$nextTick(() => {
            this.$refs[`code0`][0].focus()
          })
        }
      },
    },
    created() {},
    mounted() {},
    methods: {
      handleEnter(i) {
        if (i == 5) {
          this.requireLogin()
        }
      },
      handleBackspace(i) {
        if (!this.codes[i] && i != 0) {
          this.$refs[`code${i - 1}`][0].focus()
        }
      },
      handelNumberChange() {
        console.log('userPhone :>> ', this.userPhone)
      },
      handelCodeInputChange(i) {
        if (this.codes[i] == '' && i != 0) {
          this.$refs[`code${i - 1}`][0].focus()
        }
        if (this.codes[i] != '' && i != 5) {
          this.$refs[`code${i + 1}`][0].focus()
        }
        if (!(this.codes.includes(undefined) || this.codes.includes(''))) {
          this.requireLogin()
        }
      },
      handelNext() {
        console.log('next step', this.step)
        let regPhone = RegExp(/^\d{11}$/)
        if (this.step == 1) {
          this.phoneValidate =
            this.userPhone != '' && regPhone.test(this.userPhone)
          this.agreeValidate = this.checked
          if (this.phoneValidate && this.agreeValidate) {
            /**发送验证码 */
            this.requireCode()
          }
        } else if (this.step == 2) {
          /**检查验证码 */
          // this.codeValid = false
          /**通过验证关闭对话框 */
          this.requireLogin()
        }
      },
      showAgreement() {
        this.agreement = true
        console.log('show agreement :>> ')
      },
      showPrivacy() {
        this.privacy = true
        console.log('show privacy :>> ')
      },
      closeAgreement() {
        this.agreement = false
        this.privacy = false
      },
      agreementChange() {
        this.agreeValidate = this.checked
      },
      returnLastStep() {
        this.step -= 1
      },
      sendCode() {
        /**获取验证码 */
        this.requireCode()
        console.log('get code :>> ')
      },
      closeModel() {
        console.log('close login model :>> ')
        this.$emit('closeModel')
      },
      requireCode() {
        let params = {
          method: 'POST',
          url: 'http://chunfengai.top:28081/authorization/register/sendCmsCode',
          data: { userName: this.userPhone },
        }
        axios(params).then((res) => {
          if (res.data.code == 200) {
            this.$message({ message: '短信验证码已发送', type: 'success' })
            this.step = 2
            this.countdown = 60
            let i = setInterval(() => {
              if (this.countdown == 0) {
                clearInterval(i)
              } else {
                this.countdown -= 1
              }
            }, 1000)
          } else {
            this.$message(res.data.msg)
          }
        })
      },
      requireLogin() {
        let params = {
          method: 'POST',
          url: 'http://chunfengai.top:28081/authorization/register/smsLogin',
          data: {
            userName: this.userPhone,
            valismsCode: this.codes.join(''),
          },
        }
        axios(params).then((res) => {
          if (res.data.code == 200) {
            localStorage.setItem('userId', res.data.data.userInfo.userId)
            localStorage.setItem('token', res.data.data.token)
            this.$message({ message: '登录成功', type: 'success' })
            //
            setCookie('userId', res.data.data.userInfo.userId, 7)
            this.closeModel()
            setTimeout(() => {
              location.reload()
            }, 0)
          } else {
            this.codes = [
              undefined,
              undefined,
              undefined,
              undefined,
              undefined,
              undefined,
            ]
            this.$refs[`code0`][0].focus()
            this.$message({ message: res.data.msg, type: 'error' })
          }
        })
      },
    },
  }
</script>
<style scoped lang="less">
  .login-dialog {
  }
  .login-title {
    font-size: 20px;
    // font-weight: 600;
  }
  .login-body {
    display: flex;
    flex-direction: column;
    .phone-input {
      width: 100%;
      // height: 54px;
      border-radius: 8px 8px 8px 8px;
    }
    .phone-input-prefix {
      margin: 16px;
      line-height: 40px;
    }
  }
  .login-body-button {
    width: 100%;
    margin-top: 20px;
  }
  .login-footer-button {
    width: 100%;
  }
  .validate-falied {
    margin-top: 5px;
    color: red;
    text-align: left;
    font-size: 12px;
    &.agree {
      margin-left: 24px;
    }
  }
  .login-agreement {
    display: flex;
    align-items: center;
    margin-top: 20px;
    .agreenment-text {
      margin-bottom: 4px;
    }
  }
  .footer-agreement {
    display: flex;
    flex-direction: column;
    justify-content: start;
  }
  .agreenment {
    color: #65b0b4 !important;
  }
  .return-icon {
    margin-right: 8px;
  }
  .code-info-text {
    .info-text {
      font-size: 14px;
      font-weight: 400;
      color: #999999;
      line-height: 16px;
      float: left;
    }
    .code-resend {
      cursor: pointer;
      float: right;
      color: #65b0b4;
      &.disabled {
        color: #999999;
      }
    }
  }

  .code-container {
    display: flex;
    justify-content: space-between;
    margin-top: 16px;
    .code-single {
      width: 54px;
      opacity: 1;
    }
    .code-wrong {
    }
  }
  .login-dialog-wrapper {
    /deep/ .el-dialog {
      width: 448px;
      background: #ffffff;
      border-radius: 16px 16px 16px 16px;
    }
  }

  /deep/ .el-input--prefix .el-input__inner {
    padding-left: 60px;
  }
  /deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
    color: unset;
  }
  /deep/ .el-dialog__body {
    padding-bottom: 0px;
  }
  /deep/ .code-single .el-input__inner {
    height: 54px;
    border-radius: 8px 8px 8px 8px;
    text-align: center;
  }
</style>
